<template>
  <view class="product-page">
    <!-- 搜索栏 -->
    <!-- <view class="search-bar">
      <myInput v-model="searchTxt" @search="handleSearch" />
    </view> -->

    <!-- 分类标签 -->
    <view class="category-tabs">
      <nut-tabs v-model="activeTab" :ellipsis="false" title-scroll title-gutter="10" type="smile" @change="onTab">
        <nut-tab-pane
          :title="item.name"
          :pane-key="item.id"
          :key="item.id"
          v-for="(item, i) in cateList"
        ></nut-tab-pane>
        <!-- <nut-tab-pane title="白酒"></nut-tab-pane>
        <nut-tab-pane title="果酒"></nut-tab-pane>
        <nut-tab-pane title="礼盒"></nut-tab-pane> -->
      </nut-tabs>
    </view>

    <!-- 网格商品列表 -->
    <view class="product-grid">
      <view
        class="product-item"
        v-for="item in products"
        :key="item.id"
        @click="goToDetail(item.id)"
      >
        <image
          class="product-image"
          :src="item.image"
          mode="aspectFill"
        ></image>
        <text class="acct">{{ item.account_type }}券</text>
        <view class="product-info">
          <text class="product-title">{{ item.name }}</text>
          <text class="product-desc">{{ item.desc }}</text>
          <view class="price-row">
            <text class="price">¥{{ item.price }}</text>
            <!-- <text class="sold">{{ item.account_type }}券</text> -->
          </view>
        </view>
      </view>
    </view>
    
    <!-- 加载更多按钮 -->
    <view class="load-more" v-if="hasMore && products.length > 0">
      <nut-button 
        type="default" 
        size="small" 
        :loading="loading" 
        @click="loadMore"
      >
        {{ loading ? '加载中...' : '加载更多' }}
      </nut-button>
    </view>
    
    <!-- 没有更多数据提示 -->
    <view class="no-more" v-if="!hasMore && products.length > 0">
      <text>没有更多数据了</text>
    </view>
    
    <empty v-if="products.length === 0 && !loading" />
  </view>
</template>

<script lang="ts" setup>
import { onMounted, ref, reactive } from "vue";
import Taro from "@tarojs/taro";
const pic = "https://cdn.tjkximg.com/content/zhangtang/images/mtjx.jpg";
import myInput from "@/components/my-input/index.vue";
import http from "@/utils/http";
const searchTxt = ref("");
import empty from "@/components/empty/index.vue";
import Empty from "@/components/empty/index.vue";

function handleSearch() {
  console.log("searchTxt", searchTxt.value);
}

interface Product {
  id: number;
  name: string;
  desc: string;
  price: number;
  sold: number;
  image: string;
  account_type?: string;
  imgsUrl?: string;
}

interface CateItem {
  id: number;
  name: string;
}

interface ApiResponse {
  data: any;
  [key: string]: any;
}

const activeTab = ref<number>(0);
const cateList = ref<CateItem[]>([]);

// 分页数据管理
const pageData = reactive({
  limit: 1,
  count: 10
});

// 加载状态管理
const loading = ref(false);
const hasMore = ref(true);

const onTab = (obj: any) => {
  console.log("index", obj, activeTab.value);
  // 切换分类时重置分页
  resetPagination();
  getGoods();
};

// 重置分页数据
function resetPagination() {
  pageData.limit = 1;
  hasMore.value = true;
  products.value = [];
}

Taro.usePullDownRefresh(() => {
  resetPagination();
  getGoods();
  setTimeout(() => {
    Taro.stopPullDownRefresh();
  }, 1200);
});

const products = ref<Product[]>([]);

onMounted(() => {
  http.post(`/api/mallIndex/goodsType`).then((res: ApiResponse) => {
    console.log("res 商品类型", res);
    if (res.data && Array.isArray(res.data)) {
      cateList.value = res.data.map((i: any) => i.columns);
    }
    // getGoods(cateList.value[0].id);
  });
  
  const params = Taro.getCurrentInstance().router?.params;
  if (params && params.id) {
    activeTab.value = parseInt(params.id) || 0;
    console.log("params 路由参数", params);
    getGoods();
  }
});

function getGoods(isLoadMore = false) {
  if (loading.value) return;
  
  loading.value = true;
  const typeId = activeTab.value;
  
  http
    .postQuery(`/api/mallIndex/getGoodsByType`, { 
      typeId: typeId, 
      limit: pageData.limit, 
      count: pageData.count 
    })
    .then((res: ApiResponse) => {
      console.log("res 商品列表", res);
      
      if (res.data && Array.isArray(res.data)) {
        const newProducts = res.data.map((i: any) => i.columns);
        
        // 处理图片URL
        newProducts.forEach((item: Product) => {
          if (item.imgsUrl) {
            item.image = item.imgsUrl.split(",").pop() || pic;
          }
        });
        
        if (isLoadMore) {
          // 加载更多时追加数据
          products.value = [...products.value, ...newProducts];
        } else {
          // 首次加载或刷新时替换数据
          products.value = newProducts;
        }
        
        // 检查是否还有更多数据
        hasMore.value = newProducts.length === pageData.count;
        
        // 更新分页参数
        if (hasMore.value) {
          pageData.limit += 1;
        }
      } else {
        hasMore.value = false;
      }
    })
    .finally(() => {
      loading.value = false;
    });
}

// 加载更多功能
function loadMore() {
  if (!hasMore.value || loading.value) return;
  getGoods(true);
}

function goToDetail(id: number) {
  Taro.navigateTo({
    url: `/pages-detail/detail/index?id=${id}`,
  });
}
</script>

<style lang="scss">
.product-page {
  padding-bottom: 200rpx;

  .search-bar {
    padding: 20rpx;
    background-color: #fff;
  }

  .category-tabs {
    background-color: #fff;
    margin-bottom: 20rpx;
  }

  .product-grid {
    display: flex;
    flex-wrap: wrap;
    padding: 0 10rpx;
    box-sizing: border-box;

    .product-item {
      width: 50%;
      padding: 10rpx;
      box-sizing: border-box;
      position: relative;

      .product-image {
        width: 100%;
        height: 350rpx;
        border-radius: 16rpx 16rpx 0 0;
        background: #eee;
      }

      .product-info {
        background-color: #fff;
        padding: 20rpx;
        border-radius: 0 0 16rpx 16rpx;

        .product-title {
          font-size: 28rpx;
          font-weight: 500;
          display: -webkit-box;
          -webkit-line-clamp: 2;
          -webkit-box-orient: vertical;
          overflow: hidden;
          line-height: 40rpx;
        }

        .product-desc {
          font-size: 24rpx;
          color: #999;
          margin: 10rpx 0;
          display: block;
          line-height: 34rpx;
        }

        .price-row {
          display: flex;
          justify-content: space-between;
          align-items: center;
          margin-top: 16rpx;

          .price {
            color: #f2270c;
            font-weight: 500;
            font-size: 32rpx;
          }

          .sold {
            font-size: 24rpx;
            color: #999;
          }
        }
      }
    }
  }
  
  .acct {
    font-size: 24rpx;
    background: #008000;
    color: #fff;
    position: absolute;
    top: 8rpx;
    right: 8rpx;
    padding: 4rpx 10rpx;
    border-radius: 4rpx;
  }

  .load-more {
    padding: 40rpx 20rpx;
    text-align: center;
  }

  .no-more {
    padding: 40rpx 20rpx;
    text-align: center;
    color: #999;
    font-size: 28rpx;
  }

  .nut-tab-pane{
    display: none;
  }
}
</style>
